import datetime
import logging
import os
from api import utils, models
from api.serial import analyse, mould

logger = logging.getLogger('serial.sample')


# 每一小时运行一次
# 1小时内所有样本（含正负样本）构建样本与当前正样本画像的标准差，做连续72H推移曲线图
def process_stability_scheduler():
    current_mould = mould.CurrentMould.get_instance()
    if current_mould and current_mould.is_order_running:
        prod_mould = current_mould.prod_mould
        # var_file = os.path.join(current_mould.sample_path, 'temp', 'var.json')
        # utils.check_dir_exist(var_file)
        figure = prod_mould.get_positive()
        if figure.is_result_safe:
            try:
                N, list_len, all_feat, actual_pressure_list, actual_location_list, actual_speed_list, \
                setting_pressure_list, seg_points_list, id_list = figure.load_data_from_good_file(
                    current_mould.one_hour_temp_file, portrait_size=1000, all=True, length=figure.length)
            except Exception as e:
                logger.error(f'获取一小时内数据失败,{e}')
                return
            # 如果最小长度小于figure.length, 调整figure
            feature, var = analyse.reduce_portrait_length(figure, N)
            dist_total_mean, dist_total_var = analyse.cal_madis_list(all_feat, feature, var)
            # 这批样本马氏距离的平均值，与马氏距离的方差
            dist_total_mean, dist_total_var = dist_total_var.tolist(), dist_total_var.tolist()
            # 用该平均马氏距离对比正样本画像的mean,var
            times = analyse.cal_total_madis_times(dist_total_mean, figure.dist_total_mean, figure.dist_total_var)
            round_times = round(times, 2)
            logger.info(f"计时任务: 计算一小时内样本与当前正样本画像的标准差为{round_times}")
            utils.var_queue.append(round_times)
            # with open(var_file) as writer:
            #     json.dump(list(utils.var_queue), writer)
            try:
                os.remove(current_mould.one_hour_temp_file)
            except Exception as e:
                logger.error(e)
        else:
            logger.error("当前没有正样本画像")
    else:
        logger.error("当前没有模具在运行")


# 每周日触发，保留只本周数据，和历史数据
def clear_sample_record():
    now_time = datetime.datetime.now()
    day_num = now_time.isoweekday()
    week_day = (now_time - datetime.timedelta(days=day_num))
    # 一周前的
    try:
        logger.info("开始清除历史数据,系统只保留一周内的产品记录")
        models.Sample.objects.exclude(prod_time__gte=week_day).delete()
        logger.info("清除成功")
    except Exception as e:
        logger.error(f"清理历史记录失败,{e}")
